package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTO;
import com.atguigu.common.to.SpuBoundTO;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@SuppressWarnings("all")
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService descService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //这是一个大保存，需要保存很多数据，因此加事务
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1、保存spu基本信息 操作的表是pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfo);
        //以下两个字段使用mq的自动填充功能
//        spuInfo.setCreateTime(new Date());
//        spuInfo.setUpdateTime(new Date());
//        spuInfo.setCatalogId(vo.getCatalogId());
//        this.save(spuInfo);
        this.saveBaseSpuInfo(spuInfo);
        //2、保存spu的描述图片 操作的表是pms_spu_info_desc
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        List<String> decript = vo.getDecript();//得到的是一个集合，因为可能有多张图片描述
        String join = String.join(",", decript);//用","连接
        descEntity.setSpuId(spuInfo.getId());
        descEntity.setDecript(join);
        descService.save(descEntity);
        //3、保存spu的图片集 操作的表是pms_spu_images
//        SpuImagesEntity imagesEntity = new SpuImagesEntity();
        List<String> images = vo.getImages();
        //需要批量保存  每个spuId对应好几个图片
        imagesService.saveImages(spuInfo.getId(), images);
        //4、保存spu的规格参数【对应vo中private List<BaseAttrs> baseAttrs;字段】 操作的表是pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();//得到所有基本属性也就是规格参数
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());

            //查询attr属性名 因为属性名页面并没有提交过来
            AttrEntity byId = attrService.getById(attr.getAttrId());

            valueEntity.setAttrName(byId.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfo.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        //productAttrValueService.saveBatch(collect);也可以直接在这进行批量保存，但是为了以后的优化，采用下面方式
        productAttrValueService.saveProductAttr(collect);


        //5、保存spu的积分信息 操作的是gulimall-sms数据库，操作的表是sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(spuInfo.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if (r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        //6、保存spu对应的所有sku信息

        //6.1）、sku的基本信息 操作的表是pms_sku_info
        List<Skus> skus = vo.getSkus();
        //由于sku众多，还是采用流式遍历操作,如下表示一个sku
        //"attr": [{
        //			"attrId": 9,
        //			"attrName": "颜色",
        //			"attrValue": "黑色"
        //		}, {
        //			"attrId": 10,
        //			"attrName": "内存",
        //			"attrValue": "6GB"
        //		}],
        //		"skuName": "Apple XR 黑色 6GB",
        //		"price": "1999",
        //		"skuTitle": "Apple XR 黑色 6GB",
        //		"skuSubtitle": "Apple XR 黑色 6GB",
        //		"images": [{
        //			"imgUrl": "https://gulimall-hello.oss-cn-beijing.aliyuncs.com/2019-11-22//dcfcaec3-06d8-459b-8759-dbefc247845e_5b5e74d0978360a1.jpg",
        //			"defaultImg": 1
        //			}, {
        //			"imgUrl": "https://gulimall-hello.oss-cn-beijing.aliyuncs.com/2019-11-22//5b15e90a-a161-44ff-8e1c-9e2e09929803_749d8efdff062fb0.jpg",
        //			"defaultImg": 0
        //		}],
        //		"descar": ["黑色", "6GB"],
        //		"fullCount": 5,
        //		"discount": 0.98,
        //		"countStatus": 1,
        //		"fullPrice": 1000,
        //		"reducePrice": 10,
        //		"priceStatus": 0,
        //		"memberPrice": [{
        //			"id": 1,
        //			"name": "aaa",
        //			"price": 1998.99
        //		}]
        if (skus != null && skus.size() > 0) {

            skus.forEach(item -> {
                //找默认图片，为了后续的设置
                String defaultImage = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {//说明是默认图片
                        defaultImage = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                //private String skuName;
                //private BigDecimal price;
                //private String skuTitle;
                //private String skuSubtitle;
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);//销量，暂时设置为0
                skuInfoEntity.setSpuId(spuInfo.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                //调用service进行保存
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //sku基本信息保存完成之后，skuId就可以得出，后面和skuId有关的比如图片，因为它的skuId就是这个，并不是自增
                Long skuId = skuInfoEntity.getSkuId();

                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    //返回true就是需要，返回false就是过滤掉
                    return !StringUtils.isEmpty(entity.getImgUrl());
                })
                        .collect(Collectors.toList());
                //6.2）、sku的图片信息 操作的表是pms_sku_images
                skuImagesService.saveBatch(imagesEntities);

                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                //6.3）、sku的销售属性信息 操作的表是pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);


                //6.4）、sku的优惠，满减等信息 操作的是gulimall-sms数据库
                // 操作的表有sms_sku_ladder，sms_sku_full_reduction，sms_member_price
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                if (skuReductionTO.getFullCount() > 0 ||
                        skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfo) {
        this.baseMapper.insert(spuInfo);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        //status: 0
        //key: 1
        //brandId: 2
        //catelogId: 225

        //Preparing: SELECT id,spu_name,spu_description,catalog_id,brand_id,weight,publish_status,create_time,update_time
        // FROM pms_spu_info WHERE ((id = ? OR spu_name LIKE ?) AND publish_status = ?
        // AND brand_id = ? AND catalog_id = ?) LIMIT ?
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");//得到请求体中的检索关键字key
        if (!StringUtils.isEmpty(key)) {
            //这里加and的目的就是为了在id=1 or spu_name = '%Apple%' 这句加上（），像上面一样，如果不加的话，也就是or后面的条件成立即可了，不用管前面了
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        //优先级and>or
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            //这里可以不用andmabatisplus会自动帮我们加上
            wrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)) {
            wrapper.eq("brand_id", brandId);

        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.and(spuInfoEntityQueryWrapper -> {
                spuInfoEntityQueryWrapper.eq("catalog_id", catelogId);
            });
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    /**
     * 商品上架
     */
    @Override
    public void up(Long spuId) {
        List<SkuEsModel> list = new ArrayList<>();
        //组装需要的数据
//       SkuEsModel skuEsModel = new SkuEsModel();
        //首先查出sku的信息进行封装
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        //查询skuId的集合，为了查询库存使用
        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        //TODO 4、查询当前sku的所有规格属性，但是查询的是可以被检索的规格属性，
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrListForSpu(spuId);
        //挑出是检索属性的那些值
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        //根据attrIds去attr表中查出检索属性是1的那些属性,也就是在指定的属性集合里面，挑出检索属性
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        //从baseAttrs属性中找到符合检索属性也就是attr_id是searchAttrIds的baseAttrs
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attr> attrs = new ArrayList<>();
        List<SkuEsModel.Attr> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attr attrs1 = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());


        //TODO 1、发送远程调用，库存系统查询是否有库存，只是查询是否有，并不是精确查询
        //如果远程查询出现问题，Map就为空
        // skuId 对应 是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            // 3.1 发送远程调用 库存系统查询是否有库存
            R hasStock = wareFeignService.isExistStock(skuIdList);//k是Data，v是List，返回的是R，但是我们还想转回List

//            List<SkuHasStockVo> vos = (List<SkuHasStockVo>) hasStock.get("vos");

            // 构造器受保护 所以写成内部类对象
            stockMap = hasStock.getData(new TypeReference<List<SkuHasStockVo>>() {
            }).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            log.warn("服务调用成功" + hasStock);
        } catch (Exception e) {
            log.error("库存服务调用失败: 原因{}", e);
        }

        //封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map(item -> {
            //先封装两个实体类属性名相同的属性
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(item, skuEsModel);
            //下面处理skuInfoEntities实体类属性名不同或者没有的字段
            //skuPrice skuImg
            skuEsModel.setSkuImg(item.getSkuDefaultImg());
            skuEsModel.setSkuPrice(item.getPrice());
            //hasStock hotScore
            //TODO 1、发送远程调用，库存系统查询是否有库存，只是查询是否有，并不是精确查询
            //设置库存信息
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }
            //wareFeignService.isExistStock()
            //TODO 2、热度评分，刚上架商品是没有热度的，为了方便，先给个0
            skuEsModel.setHotScore(0L);
            //TODO 3、查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            //TODO 4、查询当前sku的所有规格属性，但是查询的是可以被检索的规格属性，
            // 但是规格属性每个spu是一样的，如果放在这里查，假如一个spu有8个sku，那么要查8遍
            // 因此将这个放到外面查询
            skuEsModel.setAttrs(attrsList);

            return skuEsModel;
        }).collect(Collectors.toList());

        //TODO 5、将数据发送给es进行保存，guliamll-search
        R r = searchFeignService.productStatusUp(collect);
        if (r.getCode() == 0) {
            //如果成功，要改掉商品上架的状态
            this.baseMapper.upSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        } else {
            log.error("商品远程es保存失败");
            //TODO 7、重复调用？接口幂等性，重试机制？xxx
            //Feign源码中是存在重试机制的
            //Feign调用流程：
            /**
             * 1、构造请求数据，将传入的对象转化为JSON
             * RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 2、发送请求进行执行(执行成功会解码响应数据)
             * executeAndDecode(template);
             * 3、执行请求会有重试机制（现在没有触发，因为默认是关闭状态）
             * while(true) {
             * try{
             * executeAndDecode(template);
             * }catch(){
             * try{
             * retryer.continueOrPropagote(e);
             * }catch(){
             * throw ex;
             * }
             * continue;
             * }
             * }
             * */
        }
    }

    /**
     * 根据skuId获取pu信息
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        return getById(skuInfoService.getById(skuId).getSpuId());
//        SkuInfoEntity byId = skuInfoService.getById(skuId);
//        Long spuId = byId.getSpuId();
//        SpuInfoEntity spuInfoEntity = this.baseMapper.selectOne(
//                new QueryWrapper<SpuInfoEntity>().eq("spu_id", spuId));
//        return spuInfoEntity;
    }
}